package persistence

import (
	"context"
	"errors"
	"time"

	"github.com/samber/do/v2"
	"gorm.io/gorm"

	"gitee.com/monkeyPP/happy-mall/services/userservice/internal/domain/entity"
	"gitee.com/monkeyPP/happy-mall/services/userservice/internal/domain/repository"
)

type User struct {
	ID        string `gorm:"primaryKey"`
	Name      string `gorm:"uniqueIndex"`
	Password  string `gorm:"size:255"`
	CreatedAt time.Time
	UpdatedAt time.Time
}

// 指定表名
func (User) TableName() string {
	return "users"
}

type UserRepository struct {
	db *gorm.DB
}

func NewUserRepository(i do.Injector) (repository.User, error) {
	db := do.MustInvoke[*gorm.DB](i)
	return &UserRepository{
		db: db,
	}, nil
}

func (u *UserRepository) Get(ctx context.Context, user *entity.User) (*entity.User, error) {
	var existUser User
	tx := u.db.WithContext(ctx).First(&existUser, "name = ?", user.Name)
	if tx.Error != nil {
		if errors.Is(tx.Error, gorm.ErrRecordNotFound) {
			return nil, nil
		}
		return nil, tx.Error
	}

	return &entity.User{
		ID:       existUser.ID,
		Name:     existUser.Name,
		Password: existUser.Password,
	}, nil
}

func (u *UserRepository) Add(ctx context.Context, user *entity.User) (*entity.User, error) {
	tx := u.db.WithContext(ctx).Create(&user)
	if tx.Error != nil {
		return nil, tx.Error
	}
	return user, nil
}
